/**
 * 用户Service
 */
package cn.antia.cep.busi;

import java.util.ArrayList;
import java.util.List;

import cn.antia.cep.common.AntiaException;
import cn.antia.cep.common.AntiaLog;
import cn.antia.cep.common.DBFlag;
import cn.antia.cep.common.SampleEncryption;
import cn.antia.cep.common.SysExceptionTool;
import cn.antia.cep.db.hibernate.bean.EmailTemp;
import cn.antia.cep.db.hibernate.bean.Role;
import cn.antia.cep.db.hibernate.bean.User;
import cn.antia.cep.db.hibernate.bean.UserRole;
import cn.antia.mail.EmailTemplate;
import cn.antia.mail.MailUtil;
import cn.antia.cep.page.po.Prole;

/**
 * @author sunkeei
 * @date Dec 18, 2007
 * @time 2:02:56 PM
 */
public class UserService extends DbHibernateService {
	/**
	 * 创建一个用户
	 * @param user
	 * @throws BusiException
	 */
	public void addUser(User user)throws BusiException{
		//设置为登录
		user.setLogonTimes(0);
		//取得注释 -- 用来激活用户
		String okey = user.getNickname();
		String mkey = SampleEncryption.getEncryptString(okey);
		String comment = xxcz(mkey);
		user.setValid(DBFlag.USER_LOCKED);
		user.setComment(comment);
		try{
			create(user);
			UserRole userRole = new UserRole();
			userRole.setRoleId((DBFlag.ROLE_NORMAL));
			userRole.setUserId(user.getId());
			create(userRole);
			//发送邮件到用户
			List list = find("from EmailTemp");
			if(list == null || list.size() < 1){
				throw new BusiException("102");
			}
			EmailTemp temp = (EmailTemp)list.get(0);
			String content = temp.getContent();
			content = content.replaceAll(EmailTemplate.USERNAME, user.getName());
			content = content.replaceAll(EmailTemplate.NICKNAME, user.getNickname());
			content = content.replaceAll(EmailTemplate.USER_UNLOCK_KEY, user.getComment());
			MailUtil.sendEmail(user.getEmail(),temp.getName(), content);
		}catch(AntiaException ae){
			AntiaLog.error("注册用户失败...");
			SysExceptionTool.addExceptionInfo(ae);
			throw new BusiException("102",ae.toString());
		}
	}
	/**
	 * 给一个用户解锁
	 * @param key
	 * @return
	 * @throws BusiException
	 */
	public User unlockUser(String key)throws BusiException{
		String hql = new StringBuffer("from User where comment = '").append(key).append("'").toString();
		List list = find(hql);
		if(list != null && list.size() == 1){
			User user = (User)list.get(0);
			user.setValid(DBFlag.VALID);
			user.setComment(null);
			update(user);
			return user;
		}else{
			throw new BusiException("101");
		}
	}
	/**
	 * 更新用户－－角色关联
	 * @param userId
	 * @param addroles
	 * @param redundant
	 */
	public void updateUserRoles(int userId,String addroles,String redundant) {
		UserRole ur;
        if(addroles != null && addroles.trim().length() > 0){
            String[] addrolearray = addroles.split("-");
            for (String anAddrolearray : addrolearray) {
                ur = new UserRole();
                ur.setUserId(userId);
                ur.setRoleId(Integer.valueOf(anAddrolearray));
                create(ur);
            }
        }
        if (redundant != null && redundant.trim().length() > 0) {
            String[] redundants = redundant.split("-");
            for (String redundant1 : redundants) {
                ur = new UserRole();
                ur.setUserId(userId);
                ur.setRoleId(Integer.valueOf(redundant1));
                remove(ur);
            }
        }
	}
	/**
	 * 查询用户拥有的角色
	 * @param userId
	 * @return
	 */
	public List<Prole> queryRolesByUser(int userId) {
		List<Prole> list = new ArrayList<Prole>();
		UserRole ur = new UserRole();
        ur.setUserId(userId);
        List urs = find(ur,false);
        List roles = find("from Role");
        Role role;
        Prole prole;
        for (Object role1 : roles) {
            role = (Role) role1;
            prole = new Prole();
            prole.setRole(role);
            if (urs != null && urs.size() > 0) {
                for (Object ur1 : urs) {
                    ur = (UserRole) ur1;
                    if (role.getId().intValue() == ur.getRoleId().intValue()) {
                        prole.setHas(true);
                        break;
                    }
                }
            }
            list.add(prole);
        }
        return list;
	}
	/**
	 * 生成乱序字符
	 *
     * @return s
     * @param s s*/
	private String xxcz(String s){
		StringBuffer ss = new StringBuffer();
		s = s.substring(10);
		char[] cs = s.toCharArray();
		for(int i = 0;i<cs.length;i++){
			ss.append(cs[i] + i);
		}
		return ss.toString();
	}
}